import HttpClient from '../../common/HttpClient';
import {ApiResult} from '../../common/ApiResult';
import {TokenResult} from "@/phr/service/auth/TokenResult";
import {SUCCESS} from "@/phr/common/ErrorCode";
import store from '@/store'

/**
 * 认证服务类
 */
class AuthService {

    private LOGIN_WITH_PASSWORD_URL = 'login/withPassword';
    private LOGIN_WITH_MESSAGECODE_URL = 'login/withCode';
    private TOKEN_VALIDATE_URL = "login/validate";
    private REGINSTER_URL = 'register/do';
    private GET_MESSAGE_CODE = 'messageCode/get';

    /**
     * 使用密码登录接口,如果登录成功后HttpClient会持有该Token，在每一次发送请求的时候都会带上该TOKEN
     * @param {string} phone 手机号
     * @param {string} password 密码
     * @returns {Promise<ApiResult<any>>} 如果登录成功返回SUCCESS
     */
    public async loginWithPassword(phone: string, password: string): Promise<ApiResult<TokenResult>> {
        return HttpClient.post<TokenResult>(this.LOGIN_WITH_PASSWORD_URL, {
            'phone': phone,
            'password': password
        }).then(res=>{
            if (res.code === SUCCESS){
                let token = res.value.token;
                store.commit("setToken",token)
            }
            return res;
        })
    }

    public async loginWithMessageCode(phone: string, code: string): Promise<ApiResult> {
        return HttpClient.post(this.LOGIN_WITH_MESSAGECODE_URL, {
            'phone': phone,
            'code': code
        }).then(res=>{
            if (res.code === SUCCESS){
                let token = res.value.token;
                store.commit("setToken",token)
            }
            return res;
        })
    }

    /**
     * 注册接口，注册成功之后返回TOKEN_RESULT，HTTP_CLIENT自动持有TOKEN
     * @param {string} phone
     * @param {string} code
     * @param {string} password
     * @param {string} idCard
     * @param {string} realName
     * @returns {Promise<ApiResult<TokenResult>>}
     */
    public async register(phone: string, code: string, password: string, idCard: string, realName: string): Promise<ApiResult<TokenResult>> {
        return HttpClient.post<TokenResult>(this.REGINSTER_URL, {
            'phone': phone,
            'code': code,
            'password': password,
            'idCard': idCard,
            'realName': realName
        }).then(res=>{
            if (res.code === SUCCESS){
                let token = res.value.token;
                store.commit("setToken",token)
            }
            return res;
        })
    }

    /**
     * 验证TOKEN是否有效
     */
    public async validateToken():Promise<ApiResult<Boolean>>{
        return HttpClient.post(this.TOKEN_VALIDATE_URL)
    }

    public async getMessageCode(phone: string): Promise<ApiResult> {
        return HttpClient.post(this.GET_MESSAGE_CODE, {
            'phone': phone
        })
    }
}

export default new AuthService()